import { fetchCors } from '../../common';
import { Album, ApiResponse, Resource } from '../types';
import { getAuthToken } from './auth';

export async function getAlbum(id: string, country?: string): Promise<Resource<Album> | null> {
	country ??= location.pathname.split('/')[1];

	const res = await fetchCors(`https://amp-api.music.apple.com/v1/catalog/${country}/albums/${id}?extend=extendedAssetUrls`, {
		headers: {
			'Origin': 'https://music.apple.com',
			'Referer': 'https://music.apple.com/',
			'Authorization': `Bearer ${await getAuthToken()}`
		}
	});

	if (res.status === 404) return null;

	const albums = await res.json<ApiResponse<Album>>();
	return albums.data[0];
}
